package com.itgo.codegen.gen;

import java.util.List;

import com.itgo.codegen.bean.ColumnMeta;
import com.itgo.codegen.bean.EntityTemplateBean;
import com.itgo.codegen.bean.TableMeta;
import com.itgo.codegen.bean.TemplateBean;
import com.itgo.codegen.config.Config;
import com.itgo.codegen.config.Config.TypeEnum;
import com.itgo.codegen.util.StringLang;

public class BeanGen extends AbstractGen{

	private TableMeta tableMeta ; 
	private boolean annotated = false ;
	public BeanGen( TableMeta tableMeta ){
		if( tableMeta == null ){
			throw new IllegalArgumentException("table meta is not empty .") ;
		}
		this.tableMeta = tableMeta ;
	}
	@Override
	protected TemplateBean build() {
		EntityTemplateBean templateBean = new EntityTemplateBean( 
				StringLang.au( Config.templateParam.getObject() ) , buildFields() , buildMethods() ) ;
		if( annotated ){
			templateBean.setTable( String.format(
					"package p ; \r\n@Table( value=\"%s\" , alias=\"%s\")", tableMeta.getTableName()  , tableMeta.getTableAliasName() ) );
		}
		return templateBean;
	}
	
	private String buildFields(){
		StringBuffer buffer = new StringBuffer("\r\n") ;
		List<ColumnMeta> columns = tableMeta.getColumnMetas() ;
		for( ColumnMeta column : columns ){
			if( annotated && column.isPk() ){
				buffer.append("\t@Id\r\n") ;
			}
			String fieldName = StringLang.tfRule( column.getColumnName() ) ;
			String javaType = TypeEnum.byDBType( column.getDataType() ).getJavaType() ;
			buffer.append( String.format("\tprivate %s %s ; \t//%s \r\n",
					javaType , fieldName , column.getColumnComment() ) ) ;
		}
		return buffer.toString() ;
	}
	
	private String buildMethods(){
		StringBuffer buffer = new StringBuffer("\r\n") ;
		List<ColumnMeta> columns = tableMeta.getColumnMetas() ;
		for( ColumnMeta column : columns ){
			String fieldName = StringLang.tfRule( column.getColumnName() ) ;
			String javaType = TypeEnum.byDBType( column.getDataType() ).getJavaType() ;
			buffer.append( String.format("\tpublic void %s ( %s %s ){ \r\n",
					StringLang.setMethodName( fieldName ) , javaType , fieldName ) ) ;
			buffer.append( String.format("\t\tthis.%s = %s ; \r\n ", fieldName , fieldName ) ) ;
			buffer.append( String.format("\t}\r\n") ) ;
			
			buffer.append( String.format("\tpublic %s %s ( ) { \r\n", 
					javaType , StringLang.getMethodName( fieldName ) ) ) ;
			buffer.append( String.format("\t\treturn this.%s ; \r\n", fieldName ) ) ;
			buffer.append( String.format("\t}\r\n") ) ;
		}
		return buffer.toString() ;
	}
	

}
